from flask import Blueprint, request, jsonify, redirect
import json
from db import db1
from .admin_user import get_data
from flask import current_app as app
from flask_mail import Mail, Message
from werkzeug.security import check_password_hash, generate_password_hash
import math

bp_user = Blueprint('user', __name__)


def send_email(title, email, content):
    mail = Mail(app)
    msg = Message(title, sender='ztlman12@163.com', recipients=[email])  # 发件人，收件人
    msg.html = content
    mail.send(msg)


@bp_user.route('/regi', methods=['POST'])
def regi():
    if request.method == 'POST':
        data = get_data()
        sql1 = '''select id from users where email = "%s" ''' % (data['email'])
        res = db1.findone(sql1)
        if res:
            return jsonify({'code': 20010, 'mes': 用户已存在})
        sql2 = '''insert into users values(0,"%s","%s",%d,"%s",%d)''' % (
            data['username'], generate_password_hash(data['password']), 0, data['email'], 0)
        print(sql2)
        db1.update(sql2)
        send_email('欢迎使用实验楼', data['email'],
                   "欢迎使用，点击以下<a href='http://localhost:5000/users/validEmail?email=" + data['email'] + "'>链接</a>验证")
        return jsonify({'code': 200})


@bp_user.route('/validEmail')
def validEmail():
    email = request.args.get('email')
    sql = '''update users set status = 1 where email = "%s" ''' % (email)
    db1.update(sql)
    return redirect('http://localhost:8888')


@bp_user.route('/cates', methods=['GET'])
def cates():
    if request.method == 'GET':
        sal = 'select id,name from cates'
        res = db1.findall(sal)
        return jsonify({'code': 200, 'list': res})


@bp_user.route('/courese', methods=['GET'])
def courese():
    if request.method == 'GET':
        where = ' where 1 = 1'
        online = request.args.get('status')
        if online:
            where = where + ' and online = ' + str(online)

        ordering = request.args.get('ordering')
        if ordering == '-create_time':
            where = where + ' and is_new = 1'
        elif ordering == '-learner':
            where = where + ' and is_host = 1'

        page = int(request.args.get('page'))
        page_size = int(request.args.get('page_size'))
        start = (page - 1) * page_size
        sql = '''select * from courses''' + where
        ''' limit %d,%d ''' % (start, page_size)
        print(sql)
        res = db1.findall(sql)
        sql1 = '''select count(id) from courses''' + where
        total = db1.findone(sql1)
        tpage = math.ceil(total['count(id)'] / page_size)
        return jsonify({'code': 200, 'list': res, 'total': tpage})
